import { Injectable } from '@nestjs/common';
import { CreatePointDto, UpdatePointDto } from './dto/point.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Point, Punch, User } from '../entities';
import { DataSource, Repository } from 'typeorm';
import {
  AdminPointPageReqDto,
  AdminPointPageResDto,
} from './dto/admin-point.dto';

@Injectable()
export class PointService {
  constructor(
    private readonly dataSource: DataSource,
    @InjectRepository(Point)
    private readonly pointRepository: Repository<Point>,
  ) {}

  async create(userId: number, data: CreatePointDto) {
    return this.pointRepository.save({ ...data, userId });
  }

  findAll(userId: number) {
    return this.pointRepository.find({
      where: { userId },
      order: {
        createdAt: 'DESC',
      },
    });
  }

  /**
   * 创建并给用户加积分
   */
  async createAndAddUserPoint(userId: number, data: CreatePointDto) {
    return await this.dataSource.transaction(async (manager) => {
      // 先创建 Point（积分）
      const point = await manager.getRepository(Point).save({
        userId,
        ...data,
      });

      // 如果传了 punchId，更新 Punch，把 pointId 关联过去
      if (data.punchId) {
        await manager.getRepository(Punch).update(data.punchId, {
          pointId: point.pointId,
        });
      }

      // 累加积分
      await manager
        .getRepository(User)
        .increment({ userId: userId }, 'totalPoint', point.count);

      return point;
    });
  }

  async findPage(
    query: AdminPointPageReqDto,
  ): Promise<AdminPointPageResDto> {
    const pageNo = query.pageNo;
    const pageSize = query.pageSize;
    const [list, total] = await this.pointRepository.findAndCount({
      skip: (pageNo - 1) * pageSize,
      take: pageSize,
      order: {
        createdAt: 'DESC',
      },
    });

    return { list, total };
  }
}
